public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}


class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}

class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int countA = count(headA);
        int countB = count(headB);
        int count = Math.min(countA, countB);
        if(countA > countB){ //使headB长度>=headA长度，便于处理
            ListNode tmp = headA;
            headA = headB;
            headB = tmp;
        }
        ListNode nodeA = headA, nodeB = headB;
        int diff = Math.abs(countA - countB);
        while(diff-- > 0){
            nodeB = nodeB.next;
        }

        for(int i = 0; i < count; i++){
            if(nodeA == nodeB){
                return nodeA;
            }
            nodeA = nodeA.next;
            nodeB = nodeB.next;
        }
        return null;
    }

    int count(ListNode head){
        ListNode node = head;
        int count = 0;
        while(node != null){
            count++;
            node = node.next;
        }
        return count;
    }
}